package com.ssy.lingxi.component.redis.utils;

import com.ssy.lingxi.component.redis.service.IRedisStringUtils;
import org.apache.commons.lang.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 流水号生成工具类
 * @author jw.chen
 * @version 2.0.0
 * @date 2020/7/23
 */
public class SerialNumberUtils {

    /**
     * 生成流水号
     * @param redisKey Redis的key
     * @param dateFormat 日期格式
     * @param numberLen 长度
     * @return 流水号
     */
    public static String getNumber(IRedisStringUtils redisStringUtils, String redisKey, Integer dbIndex, String dateFormat, Integer numberLen) {
        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
        String date = sdf.format(new Date());
        Long number = redisStringUtils.increment(redisKey, dbIndex);
        return date + StringUtils.leftPad(String.valueOf(number), numberLen, '0');
    }

    /**
     * 生成流水号(不含日期)
     * @param redisKey Redis的key
     * @param numberLen 长度
     * @return 流水号
     */
    public static String getPureNumber(IRedisStringUtils redisStringUtils, String redisKey, Integer dbIndex, Integer numberLen) {
        Long number = redisStringUtils.increment(redisKey, dbIndex);
        return StringUtils.leftPad(String.valueOf(number), numberLen, '0');
    }

    /**
     * 生成流水号(第二天从1开始)
     * @param redisKey Redis的key
     * @param numberLen 长度
     * @return 流水号
     */
    public static String getNumber(IRedisStringUtils redisStringUtils, String redisKey, Integer dbIndex, Integer numberLen) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String date = sdf.format(new Date());
        Long number = redisStringUtils.increment(redisKey, dbIndex, toZeroSeconds());
        return date + StringUtils.leftPad(String.valueOf(number), numberLen, '0');
    }

    /**
     * 获取当前时间到今晚0点的秒数
     * @return 秒数
     */
    public static long toZeroSeconds(){
        // 当前时间毫秒数
        long current = System.currentTimeMillis();
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_MONTH, 1);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        long toZero = calendar.getTimeInMillis();
        return (toZero- current) / 1000;
    }
}
